package com.opensms.mt.ms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.util.configuration.ConfigurationParametersManager;
import com.util.configuration.MissingConfigurationParameterException;

/**
 * Enviar Post a la url del API de Movistar
 * Es necesario darse de alta en el servicio de Movistar 
 * 
 * Necesita los siguientes parametros de configuracion:
 *  - EnviarAction/login: login con el que nos hemos dado de alta en el servicio de Movistar
 *  - EnviarAction/psw: psw con el que nos hemos dado de alta en el servicio de Movistar
 *  - EnviarAction/destino: url del formulario del API de Movistar
 *  - EnviarAction/referer: referer a enviar en la request
 */
public class EnviarAction {
	protected static final Log log = LogFactory.getLog(EnviarAction.class);
	
	public static String VERSION = "1.0";
	public static String LOGIN = "";
	public static String REFERER = "jukebox";
	public static String PASSWORD = "";
	public static String HOST_DESTINO ="opensms.movistar.es";
	public static String FILE_DESTINO ="/aplicacionpost/loginEnvio.jsp";
	
	
	static{
		String login = "";
		String referer = "";
		String psw = "";
		String host_destino = "";
		String file_destino = "";
		
		try{
            /* leer del fichero de configuracion: 
             * LOGIN, PSW, URL DESTINO
             */	
			login = ConfigurationParametersManager.getParameter("EnviarAction/login");
			referer = ConfigurationParametersManager.getParameter("EnviarAction/referer");
			psw = ConfigurationParametersManager.getParameter("EnviarAction/psw");
			host_destino = ConfigurationParametersManager.getParameter("EnviarAction/hostdestino");
			file_destino = ConfigurationParametersManager.getParameter("EnviarAction/filedestino");
		} catch (MissingConfigurationParameterException e) {
			log.warn("Configuracion incompleta, usando valores por defecto: " + e.getMessage());
		}
			
		LOGIN = login;
		REFERER = referer;
		PASSWORD = psw;
		HOST_DESTINO = host_destino;
		FILE_DESTINO = file_destino;
	}
	
	
	public String enviar(String tomovil, String msg) 
		throws IOException {
	
		log.debug("Abriendo URL "+HOST_DESTINO+FILE_DESTINO);
		URL urlEnvio = null;
		HttpURLConnection conexion = null;
		BufferedReader reader = null;
		try{
			//urlEnvio = new URL(DESTINO);
			
			//URL(String protocol, String host, int port, String file) 
			urlEnvio = new URL("http",HOST_DESTINO,443,FILE_DESTINO);
			
		}catch (MalformedURLException malExp){
			throw new IllegalArgumentException(malExp.toString());
		}
		
		String responseMessage="";

		try{
			log.debug("Abriendo conexion http");
			conexion = (HttpURLConnection) urlEnvio.openConnection();
			conexion.setRequestMethod("POST");
			conexion.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conexion.setRequestProperty("Connection","Close");
			conexion.setDoInput(true);
			conexion.setDoOutput(true);
			conexion.setUseCaches(false);
			conexion.setRequestProperty("User-Agent", EnviarAction.class.getName() + "/" + VERSION);
			conexion.setRequestProperty("Referer", REFERER);
			
			//rellenar datos formulario
			OutputStream ou = conexion.getOutputStream();
			OutputStreamWriter bu = new OutputStreamWriter(ou);
			bu.write("TM_ACTION=AUTHENTICATE&TM_LOGIN=" + LOGIN + "&TM_PASSWORD=" + PASSWORD +
					 "&to=" + tomovil + "&message="+URLEncoder.encode(msg, "UTF-8"));
			bu.flush();
			bu.close();
			conexion.connect();
			
			responseMessage = conexion.getResponseCode() + " - " + conexion.getResponseMessage();			
			/* ERROR STREAM ************************************* */
			if(conexion.getErrorStream()!=null){
				StringBuffer rdo2 = new StringBuffer();
				
				BufferedReader reader2 = new BufferedReader(new InputStreamReader(conexion.getErrorStream()));
				for (String line = reader2.readLine(); line != null; line = reader2.readLine()) {
					rdo2.append(line);
				}
				log.debug("ErrorInput: "+rdo2);
			}else{
				log.debug("ErrorInput: null");
			}
			/* ********************************************** */
			
			//leer la respuesta
			log.debug("Leer respuesta conexion https "+responseMessage);
			
			StringBuffer rdo = new StringBuffer();
			
			reader = new BufferedReader(new InputStreamReader(conexion.getInputStream()));
			for (String line = reader.readLine(); line != null; line = reader.readLine()) {
				rdo.append(line);
			}
			
			((HttpURLConnection)conexion).disconnect();
			return rdo.toString();
		} catch (IOException ioExp) {
			throw new IOException(responseMessage + ": " + ioExp.getMessage());
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException ignore) {};
			try{
				if (conexion!=null){
					conexion.disconnect();
				}
			}catch(Exception ignore){};
		}
	}
	
	
	public static void main (String[] args) {	
		try {
			EnviarAction action = new EnviarAction();
			String rdo = action.enviar("653183809","de tarjeta sms gratis2");
			System.out.println("Rdo test:'"+rdo+"'");
		
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.exit(0);
		}
	}
}
